const { Service } = require("egg");

class SubjectService extends Service {
    /**
     * 获取课程列表
     */
    async readList() {
        let res = await this.app.mysql.select("subject");
        return res;
    }

    /**
     * 根据课程id，查找某门课程
     * @param {string} id 课程id
     */
    async find(id) {
        let sql = "select * from subject where id = ? limit 0, 1";
        let params = [id];
        let res = await this.app.mysql.query(sql, params);
        return res[0];
    }

    /**
     * 添加一门课程
     * @param {string} name 课程名字
     */
    async create(name) {
        // 去重复
        const subject = await this.findByName(name);
        if (subject) {
            this.ctx.cast(403, "课程名称已存在");
        }
        // 随机 id
        const id = this.ctx.helper.uuid();
        // 入库
        const res = await this.app.mysql.insert("subject", {
            id,
            name,
        });
        // 返回结果
        return {
            rows: res.affectedRows,
            id: res.insertId,
        };
    }

    /**
     * 根据名称，查找课程
     * @param {string} name 课程名称
     */
    async findByName(name) {
        const sql = "select * from subject where name = ? limit 0, 1";
        const params = [name];
        const res = await this.app.mysql.query(sql, params);
        return res[0];
    }

    // 插入一个考试类型
    async createExamType(exam_name) {
        let isRepeat = await this.isRepeat("exam_name", exam_name, "exam_type");
        if (isRepeat) {
            return "repeat";
        }
        let exam_id = this.ctx.helper.randomString(2);
        let result = await this.app.mysql.insert("exam_type", {
            exam_id,
            exam_name,
        });
        return result.affectedRows;
    }
    // 验证某项在某表中是否重复
    async isRepeat(key, value, tableName) {
        let result = await this.app.mysql.select(tableName, {
            where: { [key]: value },
        });
        return result.length !== 0;
    }

    // 所有的考试类型
    async allExamType() {
        let result = await this.app.mysql.select("exam_type");
        return result;
    }
}

module.exports = SubjectService;
